"""RPA框架配置管理组件"""

import os
import webbrowser
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, 
    QGroupBox, QTreeWidget, QTreeWidgetItem, QTabWidget, QTextEdit,
    QTableWidget, QTableWidgetItem, QHeaderView, QLineEdit, 
    QComboBox, QCheckBox, QSpinBox, QDoubleSpinBox, QColorDialog,
    QFileDialog, QMessageBox, QSplitter, QToolBar, QProgressBar,
    QGridLayout, QFrame, QApplication
)
from PyQt5.QtCore import Qt, pyqtSignal, QSize, QThread
from PyQt5.QtGui import QFont, QColor, QFontMetrics

from rpa_framework.config.config_manager import ConfigManager
from rpa_framework.rpa_logging.logger import get_logger
from rpa_framework.utils.browser_driver_manager import BrowserDriverManager

logger = get_logger("rpa.gui.config_manager")


class ConfigManagerWidget(QWidget):
    """配置管理组件"""
    
    # 定义信号
    config_loaded = pyqtSignal(str)  # config_path
    config_saved = pyqtSignal(str)  # config_path
    config_changed = pyqtSignal(str, object)  # config_key, config_value
    
    def __init__(self, config_manager=None):
        super().__init__()
        
        # 使用传入的config_manager实例，如果没有则创建新实例
        if config_manager:
            self.config_manager = config_manager
            logger.info("已使用传入的ConfigManager实例")
        else:
            # 配置管理器实例
            self.config_manager = ConfigManager()
        
        # 当前配置路径
        self.current_config_path = None
        
        # 初始化UI
        self._init_ui()
        
        # 加载默认配置
        self._load_default_config()
        
        logger.info("ConfigManagerWidget初始化完成")
        
    def load_config(self):
        """加载配置文件"""
        logger.info("load_config方法被调用")
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "加载配置文件", 
            "", 
            "配置文件 (*.json *.yaml *.yml);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 加载配置
                self.config_manager.load_config(file_path)
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新配置预览
                self._update_config_preview()
                
                # 更新统计信息
                self.stats_label.setText(str(self._count_config_items(config_data)))
                
                # 更新常用配置控件
                self._update_common_config_controls()
                
                # 更新配置路径
                self.current_config_path = file_path
                self.config_path_label.setText(file_path)
                
                # 更新上次修改时间
                import os
                import datetime
                try:
                    mtime = os.path.getmtime(file_path)
                    self.modified_time_label.setText(datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S'))
                except:
                    self.modified_time_label.setText("未知")
                
                # 更新状态
                self.status_label.setText(f"已加载配置: {file_path}")
                
                # 发送信号
                self.config_loaded.emit(file_path)
                
                logger.info(f"已加载配置文件: {file_path}")
                
            except Exception as e:
                logger.error(f"加载配置文件失败: {e}")
                QMessageBox.critical(self, "错误", f"加载配置文件失败: {str(e)}")
        
        logger.info("load_config方法执行完成")
        
    def save_config(self):
        """保存配置到当前文件"""
        logger.info("save_config方法被调用")
        if not self.current_config_path:
            # 如果没有当前配置路径，调用另存为
            return self.save_config_as()
        
        try:
            # 保存配置
            self.config_manager.save_config(self.current_config_path)
            
            # 更新状态
            self.status_label.setText(f"配置已保存到: {self.current_config_path}")
            
            # 发送信号
            self.config_saved.emit(self.current_config_path)
            
            # 更新上次修改时间
            import os
            import datetime
            try:
                mtime = os.path.getmtime(self.current_config_path)
                self.modified_time_label.setText(datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S'))
            except:
                self.modified_time_label.setText("未知")
            
            logger.info(f"配置已保存到: {self.current_config_path}")
            
        except Exception as e:
            logger.error(f"保存配置失败: {e}")
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")
            
    def save_config_as(self):
        """另存为配置文件"""
        logger.info("save_config_as方法被调用")
        file_path, _ = QFileDialog.getSaveFileName(
            self, 
            "保存配置文件", 
            "", 
            "JSON文件 (*.json);;YAML文件 (*.yaml *.yml);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 确保文件扩展名
                if not any(file_path.endswith(ext) for ext in ['.json', '.yaml', '.yml']):
                    file_path += '.json'  # 默认使用JSON格式
                
                # 保存配置
                self.config_manager.save_config(file_path)
                
                # 更新当前配置路径
                self.current_config_path = file_path
                self.config_path_label.setText(file_path)
                
                # 更新状态
                self.status_label.setText(f"配置已保存到: {file_path}")
                
                # 发送信号
                self.config_saved.emit(file_path)
                
                # 更新上次修改时间
                import os
                import datetime
                try:
                    mtime = os.path.getmtime(file_path)
                    self.modified_time_label.setText(datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S'))
                except:
                    self.modified_time_label.setText("未知")
                
                logger.info(f"配置已保存到: {file_path}")
                
            except Exception as e:
                logger.error(f"保存配置失败: {e}")
                QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")
            
    def reset_to_default(self):
        """重置为默认配置"""
        logger.info("reset_to_default方法被调用")
        # 确认对话框
        reply = QMessageBox.question(
            self, 
            "确认重置", 
            "确定要将配置重置为默认值吗？当前未保存的更改将会丢失。",
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                # 重置配置
                self.config_manager.reset_to_default()
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新配置预览
                self._update_config_preview()
                
                # 更新统计信息
                self.stats_label.setText(str(self._count_config_items(config_data)))
                
                # 更新常用配置控件
                self._update_common_config_controls()
                
                # 更新状态
                self.status_label.setText("配置已重置为默认值")
                
                # 清除当前配置路径
                self.current_config_path = None
                self.config_path_label.setText("未设置")
                self.modified_time_label.setText("未知")
                
                logger.info("配置已重置为默认值")
                
            except Exception as e:
                logger.error(f"重置配置失败: {e}")
                QMessageBox.critical(self, "错误", f"重置配置失败: {str(e)}")
                
    def validate_config(self):
        """验证配置"""
        logger.info("validate_config方法被调用")
        try:
            # 验证配置
            errors = self.config_manager.validate_config()
            
            if not errors:
                self.status_label.setText("配置验证通过")
                QMessageBox.information(self, "验证结果", "配置验证通过，没有发现错误。")
            else:
                # 构建错误消息
                error_messages = []
                for key, message in errors.items():
                    error_messages.append(f"{key}: {message}")
                
                error_text = "配置验证失败，发现以下错误：\n" + "\n".join(error_messages)
                self.status_label.setText(f"配置验证失败，发现 {len(errors)} 个错误")
                QMessageBox.warning(self, "验证结果", error_text)
                
            logger.info(f"配置验证完成，发现 {len(errors)} 个错误")
            
        except Exception as e:
            logger.error(f"验证配置失败: {e}")
            QMessageBox.critical(self, "错误", f"验证配置失败: {str(e)}")
            
    def on_config_item_clicked(self, index):
        """配置项点击事件处理"""
        logger.info("on_config_item_clicked方法被调用")
        # 获取点击的项目
        item = self.config_tree.currentItem()
        if not item:
            return
            
        # 获取配置路径
        path_parts = []
        current = item
        while current:
            path_parts.insert(0, current.text(0))
            current = current.parent()
        
        # 移除根节点名称
        if path_parts:
            path_parts = path_parts[1:]
        
        config_path = ".".join(path_parts)
        logger.info(f"点击了配置项: {config_path}")
        
        # 获取配置值
        try:
            value = self.config_manager.get(config_path)
            # 更新配置预览或详细信息面板
            self._update_config_preview(config_path, value)
        except Exception as e:
            logger.error(f"获取配置项值失败: {e}")
            
    def _update_config_preview(self, path=None, value=None):
        """更新配置预览
        
        Args:
            path: 可选，指定的配置路径
            value: 可选，指定的配置值
        """
        logger.info("_update_config_preview方法被调用")
        if path is not None and value is not None:
            # 显示特定配置项的详细信息
            self.preview_text_edit.setPlainText(f"路径: {path}\n\n值: {str(value)}")
        else:
            # 显示整个配置
            try:
                config_data = self.config_manager.get_all()
                import json
                preview_text = json.dumps(config_data, ensure_ascii=False, indent=2)
                self.preview_text_edit.setPlainText(preview_text)
            except Exception as e:
                logger.error(f"更新配置预览失败: {e}")
                self.preview_text_edit.setPlainText(f"预览失败: {str(e)}")
                
    def search_config(self, keyword):
        """搜索配置项
        
        Args:
            keyword: 搜索关键词
        """
        logger.info(f"search_config方法被调用，关键词: {keyword}")
        
        if not keyword:
            # 如果关键词为空，显示所有配置
            self._update_config_tree(self.config_manager.get_all())
            return
        
        try:
            # 获取所有配置
            config_data = self.config_manager.get_all()
            
            # 递归搜索配置项
            def _search_in_dict(data, path="", results=None):
                if results is None:
                    results = {}
                
                if isinstance(data, dict):
                    for key, value in data.items():
                        full_path = f"{path}.{key}" if path else key
                        # 检查键是否包含关键词
                        if keyword.lower() in str(key).lower():
                            results[full_path] = value
                        # 递归搜索
                        _search_in_dict(value, full_path, results)
                elif isinstance(data, list):
                    for i, item in enumerate(data):
                        full_path = f"{path}[{i}]" if path else f"[{i}]"
                        # 检查列表项是否包含关键词
                        if keyword.lower() in str(item).lower():
                            results[full_path] = item
                        # 递归搜索
                        _search_in_dict(item, full_path, results)
                elif keyword.lower() in str(data).lower():
                    # 检查值是否包含关键词
                    results[path] = data
                
                return results
            
            # 执行搜索
            search_results = _search_in_dict(config_data)
            
            # 更新搜索结果显示
            if search_results:
                self.status_label.setText(f"搜索完成，找到 {len(search_results)} 个匹配项")
                # 这里可以根据需要更新UI，例如显示搜索结果列表
                # 暂时简单地在预览框中显示搜索结果
                import json
                results_text = json.dumps(search_results, ensure_ascii=False, indent=2)
                self.preview_text_edit.setPlainText(f"搜索结果 ({len(search_results)} 项):\n\n{results_text}")
            else:
                self.status_label.setText("未找到匹配的配置项")
                self.preview_text_edit.setPlainText("未找到匹配的配置项")
                
        except Exception as e:
            logger.error(f"搜索配置失败: {e}")
            self.status_label.setText("搜索配置时出错")
            QMessageBox.critical(self, "错误", f"搜索配置失败: {str(e)}")
            
    def on_value_type_changed(self, value_type):
        """值类型改变事件处理
        
        Args:
            value_type: 新的值类型
        """
        logger.info(f"on_value_type_changed方法被调用，值类型: {value_type}")
        
        # 获取当前选中的配置项
        item = self.config_tree.currentItem()
        if not item:
            return
        
        # 获取配置路径
        path_parts = []
        current = item
        while current:
            path_parts.insert(0, current.text(0))
            current = current.parent()
        
        # 移除根节点名称
        if path_parts:
            path_parts = path_parts[1:]
        
        config_path = ".".join(path_parts)
        
        try:
            # 根据选择的值类型修改配置值
            if value_type == "string":
                # 设置为空字符串
                self.config_manager.set(config_path, "")
            elif value_type == "number":
                # 设置为0
                self.config_manager.set(config_path, 0)
            elif value_type == "boolean":
                # 设置为False
                self.config_manager.set(config_path, False)
            elif value_type == "list":
                # 设置为空列表
                self.config_manager.set(config_path, [])
            elif value_type == "dict":
                # 设置为空字典
                self.config_manager.set(config_path, {})
            elif value_type == "null":
                # 设置为None
                self.config_manager.set(config_path, None)
            
            # 更新配置树
            config_data = self.config_manager.get_all()
            self._update_config_tree(config_data)
            
            # 更新预览
            self._update_config_preview()
            
            # 更新状态
            self.status_label.setText(f"已将 {config_path} 的类型更改为 {value_type}")
            
        except Exception as e:
            logger.error(f"修改配置值类型失败: {e}")
            QMessageBox.critical(self, "错误", f"修改配置值类型失败: {str(e)}")
            
    def select_color(self):
        """选择颜色并设置到当前配置项"""
        logger.info("select_color方法被调用")
        
        # 获取当前选中的配置项
        item = self.config_tree.currentItem()
        if not item:
            QMessageBox.warning(self, "警告", "请先选择一个配置项")
            return
        
        # 获取配置路径
        path_parts = []
        current = item
        while current:
            path_parts.insert(0, current.text(0))
            current = current.parent()
        
        # 移除根节点名称
        if path_parts:
            path_parts = path_parts[1:]
        
        config_path = ".".join(path_parts)
        
        try:
            # 打开颜色选择对话框
            color = QColorDialog.getColor()
            
            if color.isValid():
                # 获取颜色的十六进制值
                color_hex = color.name()
                
                # 设置到配置
                self.config_manager.set(config_path, color_hex)
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText(f"已设置 {config_path} 的颜色为 {color_hex}")
                
                logger.info(f"已设置颜色: {color_hex} 到配置项: {config_path}")
                
        except Exception as e:
            logger.error(f"选择颜色失败: {e}")
            QMessageBox.critical(self, "错误", f"选择颜色失败: {str(e)}")
            
    def select_file(self):
        """选择文件并设置到当前配置项"""
        logger.info("select_file方法被调用")
        
        # 获取当前选中的配置项
        item = self.config_tree.currentItem()
        if not item:
            QMessageBox.warning(self, "警告", "请先选择一个配置项")
            return
        
        # 获取配置路径
        path_parts = []
        current = item
        while current:
            path_parts.insert(0, current.text(0))
            current = current.parent()
        
        # 移除根节点名称
        if path_parts:
            path_parts = path_parts[1:]
        
        config_path = ".".join(path_parts)
        
        try:
            # 打开文件选择对话框
            file_path, _ = QFileDialog.getOpenFileName(
                self,
                "选择文件",
                "",
                "所有文件 (*.*)"
            )
            
            if file_path:
                # 设置到配置
                self.config_manager.set(config_path, file_path)
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText(f"已设置 {config_path} 的文件路径为: {file_path}")
                
                logger.info(f"已设置文件路径: {file_path} 到配置项: {config_path}")
                
        except Exception as e:
            logger.error(f"选择文件失败: {e}")
            QMessageBox.critical(self, "错误", f"选择文件失败: {str(e)}")
            
    def select_directory(self):
        """选择目录并设置到当前配置项"""
        logger.info("select_directory方法被调用")
        
        # 获取当前选中的配置项
        item = self.config_tree.currentItem()
        if not item:
            QMessageBox.warning(self, "警告", "请先选择一个配置项")
            return
        
        # 获取配置路径
        path_parts = []
        current = item
        while current:
            path_parts.insert(0, current.text(0))
            current = current.parent()
        
        # 移除根节点名称
        if path_parts:
            path_parts = path_parts[1:]
        
        config_path = ".".join(path_parts)
        
        try:
            # 打开目录选择对话框
            directory_path = QFileDialog.getExistingDirectory(
                self,
                "选择目录",
                ""
            )
            
            if directory_path:
                # 设置到配置
                self.config_manager.set(config_path, directory_path)
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText(f"已设置 {config_path} 的目录路径为: {directory_path}")
                
                logger.info(f"已设置目录路径: {directory_path} 到配置项: {config_path}")
                
        except Exception as e:
            logger.error(f"选择目录失败: {e}")
            QMessageBox.critical(self, "错误", f"选择目录失败: {str(e)}")
            
    def apply_changes(self):
        """应用所有配置更改"""
        logger.info("apply_changes方法被调用")
        
        try:
            # 保存配置
            self.config_manager.save()
            
            # 更新状态
            self.status_label.setText("配置更改已应用并保存")
            
            logger.info("配置更改已成功应用并保存")
            
            # 显示成功消息
            QMessageBox.information(self, "成功", "配置更改已应用并保存")
            
        except Exception as e:
            logger.error(f"应用配置更改失败: {e}")
            QMessageBox.critical(self, "错误", f"应用配置更改失败: {str(e)}")
            
    def export_config(self):
        """导出配置到文件"""
        logger.info("export_config方法被调用")
        
        try:
            # 获取配置数据
            config_data = self.config_manager.get_all()
            
            # 打开文件保存对话框
            file_path, _ = QFileDialog.getSaveFileName(
                self,
                "导出配置",
                "config.json",
                "JSON文件 (*.json);;YAML文件 (*.yaml);;所有文件 (*.*)"
            )
            
            if file_path:
                # 根据文件扩展名选择格式
                with open(file_path, 'w', encoding='utf-8') as f:
                    if file_path.endswith('.json'):
                        import json
                        json.dump(config_data, f, ensure_ascii=False, indent=2)
                    elif file_path.endswith('.yaml') or file_path.endswith('.yml'):
                        import yaml
                        yaml.dump(config_data, f, allow_unicode=True, default_flow_style=False)
                    else:
                        # 默认使用JSON格式
                        import json
                        json.dump(config_data, f, ensure_ascii=False, indent=2)
                
                # 更新状态
                self.status_label.setText(f"配置已导出到: {file_path}")
                
                logger.info(f"配置已导出到: {file_path}")
                
                # 显示成功消息
                QMessageBox.information(self, "成功", f"配置已成功导出到: {file_path}")
                
        except Exception as e:
            logger.error(f"导出配置失败: {e}")
            QMessageBox.critical(self, "错误", f"导出配置失败: {str(e)}")
            
    def import_config(self):
        """从文件导入配置"""
        logger.info("import_config方法被调用")
        
        try:
            # 打开文件选择对话框
            file_path, _ = QFileDialog.getOpenFileName(
                self,
                "导入配置",
                "",
                "配置文件 (*.json *.yaml *.yml);;所有文件 (*.*)"
            )
            
            if file_path:
                # 读取配置文件
                with open(file_path, 'r', encoding='utf-8') as f:
                    if file_path.endswith('.json'):
                        import json
                        config_data = json.load(f)
                    elif file_path.endswith('.yaml') or file_path.endswith('.yml'):
                        import yaml
                        config_data = yaml.safe_load(f)
                    else:
                        # 默认尝试JSON格式
                        import json
                        config_data = json.load(f)
                
                # 设置配置
                self.config_manager.set_all(config_data)
                
                # 保存配置
                self.config_manager.save()
                
                # 更新配置树
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText(f"配置已从: {file_path} 导入")
                
                logger.info(f"配置已从: {file_path} 导入")
                
                # 显示成功消息
                QMessageBox.information(self, "成功", f"配置已成功从: {file_path} 导入")
                
        except Exception as e:
            logger.error(f"导入配置失败: {e}")
            QMessageBox.critical(self, "错误", f"导入配置失败: {str(e)}")
            
    def apply_common_config(self):
        """应用通用配置"""
        logger.info("apply_common_config方法被调用")
        
        try:
            # 获取通用配置项（这里假设通用配置存储在common节点下）
            common_config = self.config_manager.get("common", {})
            
            if common_config:
                # 应用通用配置到系统
                for key, value in common_config.items():
                    self.config_manager.set(key, value)
                
                # 保存配置
                self.config_manager.save()
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText("通用配置已应用")
                
                logger.info(f"通用配置已成功应用，配置项数量: {len(common_config)}")
                
                # 显示成功消息
                QMessageBox.information(self, "成功", "通用配置已成功应用")
            else:
                self.status_label.setText("未找到通用配置项")
                logger.warning("未找到通用配置项")
                QMessageBox.information(self, "信息", "未找到通用配置项")
                
        except Exception as e:
            logger.error(f"应用通用配置失败: {e}")
            QMessageBox.critical(self, "错误", f"应用通用配置失败: {str(e)}")
            
    def reset_config(self):
        """重置配置到默认值"""
        logger.info("reset_config方法被调用")
        
        try:
            # 确认重置操作
            reply = QMessageBox.question(
                self,
                "确认重置",
                "确定要重置所有配置到默认值吗？这将清除所有自定义配置。",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # 重置配置管理器
                self.config_manager.reset()
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新预览
                self._update_config_preview()
                
                # 更新状态
                self.status_label.setText("配置已重置到默认值")
                
                logger.info("配置已成功重置到默认值")
                
                # 显示成功消息
                QMessageBox.information(self, "成功", "配置已成功重置到默认值")
                
        except Exception as e:
            logger.error(f"重置配置失败: {e}")
            QMessageBox.critical(self, "错误", f"重置配置失败: {str(e)}")
    
    def _init_ui(self):
        """初始化UI组件"""
        main_layout = QVBoxLayout(self)
        
        # 工具栏
        toolbar = QToolBar("配置管理器工具栏")
        
        # 加载配置
        load_action = QPushButton("加载配置")
        load_action.clicked.connect(self.load_config)
        toolbar.addWidget(load_action)
        
        # 保存配置
        save_action = QPushButton("保存配置")
        save_action.clicked.connect(self.save_config)
        toolbar.addWidget(save_action)
        
        # 保存为
        save_as_action = QPushButton("另存为")
        save_as_action.clicked.connect(self.save_config_as)
        toolbar.addWidget(save_as_action)
        
        # 重置配置
        reset_action = QPushButton("重置为默认值")
        reset_action.clicked.connect(self.reset_to_default)
        toolbar.addWidget(reset_action)
        
        # 验证配置
        validate_action = QPushButton("验证配置")
        validate_action.clicked.connect(self.validate_config)
        toolbar.addWidget(validate_action)
        
        main_layout.addWidget(toolbar)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # 左侧配置树
        tree_widget = QWidget()
        tree_layout = QVBoxLayout(tree_widget)
        
        tree_group = QGroupBox("配置项")
        tree_group_layout = QVBoxLayout(tree_group)
        
        self.config_tree = QTreeWidget()
        self.config_tree.setHeaderLabel("配置项")
        self.config_tree.setColumnCount(2)
        self.config_tree.setHeaderLabels(["配置项", "值"])
        self.config_tree.setColumnWidth(0, 200)
        
        # 设置点击事件
        self.config_tree.itemClicked.connect(self.on_config_item_clicked)
        
        tree_group_layout.addWidget(self.config_tree)
        tree_layout.addWidget(tree_group)
        
        # 搜索功能
        search_layout = QHBoxLayout()
        search_label = QLabel("搜索:")
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("输入配置项名称...")
        self.search_edit.textChanged.connect(self.search_config)
        
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_edit)
        tree_layout.addLayout(search_layout)
        
        tree_layout.addStretch()
        
        # 添加到分割器
        splitter.addWidget(tree_widget)
        
        # 右侧配置详情
        details_widget = QWidget()
        details_layout = QVBoxLayout(details_widget)
        
        # 配置详情标签页
        self.details_tabs = QTabWidget()
        
        # 基本信息标签页
        self.info_tab = QWidget()
        self.info_layout = QVBoxLayout(self.info_tab)
        
        # 配置基本信息
        info_group = QGroupBox("配置信息")
        info_group_layout = QVBoxLayout(info_group)
        
        # 配置路径
        path_layout = QHBoxLayout()
        path_layout.addWidget(QLabel("配置路径:"))
        self.config_path_label = QLabel("未设置")
        self.config_path_label.setWordWrap(True)
        path_layout.addWidget(self.config_path_label)
        info_group_layout.addLayout(path_layout)
        
        # 上次修改时间
        modified_layout = QHBoxLayout()
        modified_layout.addWidget(QLabel("上次修改:"))
        self.modified_time_label = QLabel("未知")
        modified_layout.addWidget(self.modified_time_label)
        info_group_layout.addLayout(modified_layout)
        
        # 配置统计
        stats_layout = QHBoxLayout()
        stats_layout.addWidget(QLabel("配置项数量:"))
        self.stats_label = QLabel("0")
        stats_layout.addWidget(self.stats_label)
        stats_layout.addStretch()
        info_group_layout.addLayout(stats_layout)
        
        self.info_layout.addWidget(info_group)
        
        # 配置编辑器
        editor_group = QGroupBox("配置编辑器")
        editor_layout = QVBoxLayout(editor_group)
        
        # 配置键
        key_layout = QHBoxLayout()
        key_layout.addWidget(QLabel("配置键:"))
        self.config_key_edit = QLineEdit()
        self.config_key_edit.setReadOnly(True)
        key_layout.addWidget(self.config_key_edit)
        editor_layout.addLayout(key_layout)
        
        # 配置值类型
        type_layout = QHBoxLayout()
        type_layout.addWidget(QLabel("值类型:"))
        self.config_type_combo = QComboBox()
        self.config_type_combo.addItems(["字符串", "整数", "浮点数", "布尔值", "列表", "字典", "颜色", "文件路径"])
        self.config_type_combo.currentIndexChanged.connect(self.on_value_type_changed)
        type_layout.addWidget(self.config_type_combo)
        editor_layout.addLayout(type_layout)
        
        # 配置值编辑器容器
        self.value_editor_container = QWidget()
        self.value_editor_layout = QVBoxLayout(self.value_editor_container)
        
        # 默认值编辑器 - 字符串
        self.string_edit = QLineEdit()
        self.value_editor_layout.addWidget(QLabel("值:"))
        self.value_editor_layout.addWidget(self.string_edit)
        
        # 其他类型的编辑器将在运行时添加
        self.int_spin = QSpinBox()
        self.int_spin.setRange(-1000000, 1000000)
        self.int_spin.setVisible(False)
        
        self.float_spin = QDoubleSpinBox()
        self.float_spin.setRange(-1000000.0, 1000000.0)
        self.float_spin.setDecimals(4)
        self.float_spin.setVisible(False)
        
        self.bool_check = QCheckBox("值")
        self.bool_check.setVisible(False)
        
        self.list_edit = QTextEdit()
        self.list_edit.setPlaceholderText("每行输入一个元素")
        self.list_edit.setVisible(False)
        
        self.dict_edit = QTextEdit()
        self.dict_edit.setPlaceholderText("每行输入一个键值对，格式为: key=value")
        self.dict_edit.setVisible(False)
        
        self.color_button = QPushButton("选择颜色")
        self.color_button.clicked.connect(self.select_color)
        self.color_button.setVisible(False)
        
        self.file_button = QPushButton("选择文件")
        self.file_button.clicked.connect(self.select_file)
        self.file_button.setVisible(False)
        
        editor_layout.addWidget(self.value_editor_container)
        
        # 应用按钮
        apply_layout = QHBoxLayout()
        apply_layout.addStretch()
        
        self.apply_button = QPushButton("应用更改")
        self.apply_button.clicked.connect(self.apply_changes)
        self.apply_button.setEnabled(False)
        apply_layout.addWidget(self.apply_button)
        
        editor_layout.addLayout(apply_layout)
        
        self.info_layout.addWidget(editor_group)
        self.info_layout.addStretch()
        
        self.details_tabs.addTab(self.info_tab, "基本信息")
        
        # 配置预览标签页
        self.preview_tab = QWidget()
        self.preview_layout = QVBoxLayout(self.preview_tab)
        
        preview_group = QGroupBox("配置预览")
        preview_group_layout = QVBoxLayout(preview_group)
        
        self.preview_text = QTextEdit()
        self.preview_text.setReadOnly(True)
        preview_group_layout.addWidget(self.preview_text)
        
        self.preview_layout.addWidget(preview_group)
        
        self.details_tabs.addTab(self.preview_tab, "配置预览")
        
        # 常用配置标签页
        self.common_tab = QWidget()
        self.common_layout = QVBoxLayout(self.common_tab)
        
        common_group = QGroupBox("常用配置")
        common_group_layout = QVBoxLayout(common_group)
        
        # 日志配置
        log_group = QGroupBox("日志配置")
        log_group_layout = QVBoxLayout(log_group)
        
        # 日志级别
        log_level_layout = QHBoxLayout()
        log_level_layout.addWidget(QLabel("日志级别:"))
        self.log_level_combo = QComboBox()
        self.log_level_combo.addItems(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"])
        log_level_layout.addWidget(self.log_level_combo)
        log_group_layout.addLayout(log_level_layout)
        
        # 日志文件
        log_file_layout = QHBoxLayout()
        log_file_layout.addWidget(QLabel("日志文件:"))
        self.log_file_edit = QLineEdit()
        log_file_layout.addWidget(self.log_file_edit)
        log_file_button = QPushButton("浏览...")
        log_file_button.clicked.connect(lambda: self._browse_file(self.log_file_edit))
        log_file_layout.addWidget(log_file_button)
        log_group_layout.addLayout(log_file_layout)
        
        # 日志轮转
        log_rotate_layout = QHBoxLayout()
        log_rotate_layout.addWidget(QLabel("日志轮转:"))
        self.log_rotate_check = QCheckBox()
        log_rotate_layout.addWidget(self.log_rotate_check)
        log_group_layout.addLayout(log_rotate_layout)
        
        common_group_layout.addWidget(log_group)
        
        # 机器人配置
        robot_group = QGroupBox("机器人配置")
        robot_group_layout = QVBoxLayout(robot_group)
        
        # 默认超时
        timeout_layout = QHBoxLayout()
        timeout_layout.addWidget(QLabel("默认超时(秒):"))
        self.default_timeout_spin = QSpinBox()
        self.default_timeout_spin.setRange(1, 3600)
        self.default_timeout_spin.setValue(300)
        timeout_layout.addWidget(self.default_timeout_spin)
        robot_group_layout.addLayout(timeout_layout)
        
        # 重试次数
        retry_layout = QHBoxLayout()
        retry_layout.addWidget(QLabel("默认重试次数:"))
        self.default_retry_spin = QSpinBox()
        self.default_retry_spin.setRange(0, 10)
        self.default_retry_spin.setValue(3)
        retry_layout.addWidget(self.default_retry_spin)
        robot_group_layout.addLayout(retry_layout)
        
        # 重试间隔
        retry_interval_layout = QHBoxLayout()
        retry_interval_layout.addWidget(QLabel("重试间隔(秒):"))
        self.retry_interval_spin = QDoubleSpinBox()
        self.retry_interval_spin.setRange(0.1, 60)
        self.retry_interval_spin.setValue(1.0)
        retry_interval_layout.addWidget(self.retry_interval_spin)
        robot_group_layout.addLayout(retry_interval_layout)
        
        common_group_layout.addWidget(robot_group)
        
        # 常用配置应用按钮
        common_apply_layout = QHBoxLayout()
        common_apply_layout.addStretch()
        
        self.common_apply_button = QPushButton("应用常用配置")
        self.common_apply_button.clicked.connect(self.apply_common_config)
        common_apply_layout.addWidget(self.common_apply_button)
        
        common_group_layout.addLayout(common_apply_layout)
        
        self.common_layout.addWidget(common_group)
        self.common_layout.addStretch()
        
        self.details_tabs.addTab(self.common_tab, "常用配置")
        
        # 浏览器驱动管理标签页
        self.driver_tab = QWidget()
        self.driver_layout = QVBoxLayout(self.driver_tab)
        
        # 初始化浏览器驱动管理器
        self.driver_manager = BrowserDriverManager()
        
        # 驱动信息表格
        driver_table_group = QGroupBox("浏览器驱动管理")
        driver_table_layout = QVBoxLayout(driver_table_group)
        
        self.driver_table = QTableWidget()
        self.driver_table.setColumnCount(6)
        self.driver_table.setHorizontalHeaderLabels([
            "浏览器", "浏览器状态", "驱动状态", "驱动版本", "操作", "驱动下载"
        ])
        
        # 设置表格列宽
        header = self.driver_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.Stretch)
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
        
        driver_table_layout.addWidget(self.driver_table)
        
        # 刷新按钮
        refresh_layout = QHBoxLayout()
        refresh_layout.addStretch()
        self.refresh_drivers_button = QPushButton("刷新驱动列表")
        self.refresh_drivers_button.clicked.connect(self.refresh_driver_table)
        refresh_layout.addWidget(self.refresh_drivers_button)
        driver_table_layout.addLayout(refresh_layout)
        
        self.driver_layout.addWidget(driver_table_group)
        
        # 驱动目录设置
        driver_dir_group = QGroupBox("驱动目录设置")
        driver_dir_layout = QHBoxLayout(driver_dir_group)
        
        driver_dir_layout.addWidget(QLabel("驱动存储目录:"))
        self.driver_dir_edit = QLineEdit(str(self.driver_manager.driver_dir))
        self.driver_dir_edit.setReadOnly(True)
        driver_dir_layout.addWidget(self.driver_dir_edit)
        
        change_dir_button = QPushButton("更改...")
        change_dir_button.clicked.connect(self.change_driver_directory)
        driver_dir_layout.addWidget(change_dir_button)
        
        self.driver_layout.addWidget(driver_dir_group)
        
        # 系统信息
        system_info_group = QGroupBox("系统信息")
        system_info_layout = QHBoxLayout(system_info_group)
        
        import platform
        system_info = f"操作系统: {platform.system()} {platform.version()}, 架构: {platform.architecture()[0]}"
        system_info_label = QLabel(system_info)
        system_info_layout.addWidget(system_info_label)
        system_info_layout.addStretch()
        
        self.driver_layout.addWidget(system_info_group)
        
        # 状态信息
        self.driver_status_label = QLabel("就绪")
        status_layout = QHBoxLayout()
        status_layout.addWidget(self.driver_status_label)
        status_layout.addStretch()
        
        self.driver_layout.addLayout(status_layout)
        
        self.details_tabs.addTab(self.driver_tab, "浏览器驱动管理")
        
        # 初始化驱动表格
        self.refresh_driver_table()
        
        details_layout.addWidget(self.details_tabs)
        
        # 添加到分割器
        splitter.addWidget(details_widget)
        
        # 设置分割器比例
        splitter.setSizes([300, 700])
        
        main_layout.addWidget(splitter)
        
        # 状态栏
        status_layout = QHBoxLayout()
        self.status_label = QLabel("就绪")
        status_layout.addWidget(self.status_label)
        status_layout.addStretch()
        
        main_layout.addLayout(status_layout)
    
    def _load_default_config(self):
        """加载默认配置"""
        # 获取配置数据
        config_data = self.config_manager.get_all()
        
        # 更新配置树
        self._update_config_tree(config_data)
        
        # 更新配置预览
        self._update_config_preview()
        
        # 更新统计信息
        self.stats_label.setText(str(self._count_config_items(config_data)))
        
        # 更新常用配置控件
        self._update_common_config_controls()
    
    def _update_config_tree(self, config_data, parent_item=None, path=""):
        """更新配置树"""
        if parent_item is None:
            self.config_tree.clear()
        
        if isinstance(config_data, dict):
            for key, value in config_data.items():
                new_path = f"{path}.{key}" if path else key
                item = QTreeWidgetItem([key, str(value)])
                
                # 如果没有父项，直接添加到树
                if parent_item is None:
                    self.config_tree.addTopLevelItem(item)
                else:
                    parent_item.addChild(item)
                
                # 如果值是嵌套的字典或列表，递归添加
                if isinstance(value, (dict, list)):
                    self._update_config_tree(value, item, new_path)
                
                # 展开顶层节点
                if not path:
                    item.setExpanded(True)
        elif isinstance(config_data, list):
            for i, value in enumerate(config_data):
                new_path = f"{path}[{i}]"
                item = QTreeWidgetItem([f"[{i}]", str(value)])
                
                # 如果没有父项，直接添加到树
                if parent_item is None:
                    self.config_tree.addTopLevelItem(item)
                else:
                    parent_item.addChild(item)
                
                # 如果值是嵌套的字典或列表，递归添加
                if isinstance(value, (dict, list)):
                    self._update_config_tree(value, item, new_path)
    
    def _count_config_items(self, config_data):
        """统计配置项数量"""
        count = 0
        
        if isinstance(config_data, dict):
            for value in config_data.values():
                count += 1
                if isinstance(value, (dict, list)):
                    count += self._count_config_items(value)
        elif isinstance(config_data, list):
            for value in config_data:
                count += 1
                if isinstance(value, (dict, list)):
                    count += self._count_config_items(value)
        
        return count
    
    def _update_config_preview(self):
        """更新配置预览"""
        import json
        
        try:
            # 获取配置数据
            config_data = self.config_manager.get_all()
            
            # 格式化JSON
            formatted_json = json.dumps(config_data, indent=2, ensure_ascii=False)
            
            # 更新预览文本
            self.preview_text.setText(formatted_json)
        except Exception as e:
            logger.error(f"更新配置预览失败: {e}")
            self.preview_text.setText(f"预览失败: {str(e)}")
    
    def _update_common_config_controls(self):
        """更新常用配置控件"""
        # 获取日志配置
        log_level = self.config_manager.get("logging.level", "INFO")
        log_file = self.config_manager.get("logging.file", "rpa.log")
        log_rotate = self.config_manager.get("logging.rotate", True)
        
        # 更新控件
        self.log_level_combo.setCurrentText(log_level)
        self.log_file_edit.setText(log_file)
        self.log_rotate_check.setChecked(log_rotate)
        
        # 获取机器人配置
        default_timeout = self.config_manager.get("robot.default_timeout", 300)
        default_retry = self.config_manager.get("robot.default_retry", 3)
        retry_interval = self.config_manager.get("robot.retry_interval", 1.0)
        
        # 更新控件
        self.default_timeout_spin.setValue(default_timeout)
        self.default_retry_spin.setValue(default_retry)
        self.retry_interval_spin.setValue(retry_interval)
    
    def refresh_driver_table(self):
        """刷新驱动表格"""
        # 清空表格
        self.driver_table.setRowCount(0)
        
        # 获取浏览器信息
        browsers_info = self.driver_manager.get_browser_info()
        
        # 添加到表格
        for i, browser in enumerate(browsers_info):
            self.driver_table.insertRow(i)
            
            # 浏览器名称
            name_item = QTableWidgetItem(browser["name"])
            name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
            self.driver_table.setItem(i, 0, name_item)
            
            # 浏览器状态
            status_item = QTableWidgetItem("已安装" if browser["installed"] else "未安装")
            status_item.setFlags(status_item.flags() & ~Qt.ItemIsEditable)
            # 设置颜色
            if browser["installed"]:
                status_item.setForeground(Qt.green)
            else:
                status_item.setForeground(Qt.red)
            self.driver_table.setItem(i, 1, status_item)
            
            # 驱动状态
            driver_status_item = QTableWidgetItem("已安装" if browser["driver_installed"] else "未安装")
            driver_status_item.setFlags(driver_status_item.flags() & ~Qt.ItemIsEditable)
            if browser["driver_installed"]:
                driver_status_item.setForeground(Qt.green)
            else:
                driver_status_item.setForeground(Qt.red)
            self.driver_table.setItem(i, 2, driver_status_item)
            
            # 驱动版本
            if browser["driver_installed"]:
                version = self.driver_manager.check_driver_version(browser["type"])
                version_item = QTableWidgetItem(version or "未知")
            else:
                version_item = QTableWidgetItem("-")
            version_item.setFlags(version_item.flags() & ~Qt.ItemIsEditable)
            self.driver_table.setItem(i, 3, version_item)
            
            # 操作按钮
            operation_widget = QWidget()
            operation_layout = QHBoxLayout(operation_widget)
            operation_layout.setContentsMargins(5, 2, 5, 2)
            
            if browser["driver_installed"]:
                # 更新按钮
                update_button = QPushButton("更新")
                update_button.setFixedSize(60, 25)
                update_button.clicked.connect(lambda checked, b=browser["type"]: self.update_driver(b))
                operation_layout.addWidget(update_button)
                
                # 删除按钮
                remove_button = QPushButton("删除")
                remove_button.setFixedSize(60, 25)
                remove_button.clicked.connect(lambda checked, b=browser["type"]: self.remove_driver(b))
                operation_layout.addWidget(remove_button)
            else:
                # 安装按钮
                install_button = QPushButton("安装")
                install_button.setFixedSize(60, 25)
                install_button.clicked.connect(lambda checked, b=browser["type"]: self.install_driver(b))
                operation_layout.addWidget(install_button)
            
            operation_widget.setLayout(operation_layout)
            self.driver_table.setCellWidget(i, 4, operation_widget)
            
            # 驱动下载链接按钮
            download_widget = QWidget()
            download_layout = QHBoxLayout(download_widget)
            download_layout.setContentsMargins(5, 2, 5, 2)
            
            download_button = QPushButton("官方下载")
            download_button.setFixedSize(80, 25)
            download_button.clicked.connect(lambda checked, url=browser["driver_download_url"]: self.open_download_url(url))
            download_layout.addWidget(download_button)
            
            download_widget.setLayout(download_layout)
            self.driver_table.setCellWidget(i, 5, download_widget)
        
        # 更新状态
        self.driver_status_label.setText("驱动列表已刷新")
    
    def install_driver(self, browser_type):
        """安装驱动"""
        self.driver_status_label.setText(f"正在安装{self._get_browser_name(browser_type)}驱动...")
        QApplication.processEvents()
        
        # 在新线程中执行下载以避免UI冻结
        self.driver_thread = DriverOperationThread(self.driver_manager, "install", browser_type)
        self.driver_thread.finished.connect(lambda success: self.on_driver_operation_finished(success, "安装", browser_type))
        self.driver_thread.start()
    
    def update_driver(self, browser_type):
        """更新驱动"""
        self.driver_status_label.setText(f"正在更新{self._get_browser_name(browser_type)}驱动...")
        QApplication.processEvents()
        
        # 在新线程中执行更新以避免UI冻结
        self.driver_thread = DriverOperationThread(self.driver_manager, "update", browser_type)
        self.driver_thread.finished.connect(lambda success: self.on_driver_operation_finished(success, "更新", browser_type))
        self.driver_thread.start()
    
    def remove_driver(self, browser_type):
        """删除驱动"""
        reply = QMessageBox.question(
            self, 
            "确认删除", 
            f"确定要删除{self._get_browser_name(browser_type)}驱动吗？",
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            success = self.driver_manager.remove_driver(browser_type)
            if success:
                self.driver_status_label.setText(f"已删除{self._get_browser_name(browser_type)}驱动")
                self.refresh_driver_table()
            else:
                self.driver_status_label.setText(f"删除{self._get_browser_name(browser_type)}驱动失败")
    
    def change_driver_directory(self):
        """更改驱动目录"""
        from PyQt5.QtWidgets import QFileDialog
        
        new_dir = QFileDialog.getExistingDirectory(self, "选择驱动存储目录")
        if new_dir:
            try:
                # 更新驱动管理器的目录
                self.driver_manager = BrowserDriverManager(new_dir)
                self.driver_dir_edit.setText(str(self.driver_manager.driver_dir))
                self.driver_status_label.setText(f"驱动目录已更改为: {new_dir}")
                self.refresh_driver_table()
                
                # 更新配置
                self.config_manager.set("browser.driver_directory", new_dir)
            except Exception as e:
                self.driver_status_label.setText(f"更改驱动目录失败: {str(e)}")
                QMessageBox.critical(self, "错误", f"更改驱动目录失败: {str(e)}")
    
    def open_download_url(self, url):
        """打开下载链接"""
        try:
            webbrowser.open(url)
            self.driver_status_label.setText(f"已打开下载页面: {url}")
        except Exception as e:
            self.driver_status_label.setText(f"无法打开下载页面: {str(e)}")
    
    def on_driver_operation_finished(self, success, operation, browser_type):
        """驱动操作完成回调"""
        browser_name = self._get_browser_name(browser_type)
        if success:
            self.driver_status_label.setText(f"{operation}{browser_name}驱动成功")
            self.refresh_driver_table()
        else:
            self.driver_status_label.setText(f"{operation}{browser_name}驱动失败")
            QMessageBox.critical(self, "错误", f"{operation}{browser_name}驱动失败，请检查网络连接或权限")
    
    def _get_browser_name(self, browser_type):
        """根据浏览器类型获取浏览器名称"""
        browser_names = {
            "chrome": "Chrome",
            "firefox": "Firefox",
            "edge": "Edge"
        }
        return browser_names.get(browser_type, browser_type)


class DriverOperationThread(QThread):
    """驱动操作线程"""
    finished = pyqtSignal(bool)
    
    def __init__(self, driver_manager, operation, browser_type):
        super().__init__()
        self.driver_manager = driver_manager
        self.operation = operation
        self.browser_type = browser_type
    
    def run(self):
        """执行驱动操作"""
        try:
            if self.operation == "install":
                success = self.driver_manager.download_driver(self.browser_type)
            elif self.operation == "update":
                success = self.driver_manager.update_driver(self.browser_type)
            else:
                success = False
            
            self.finished.emit(success)
        except Exception as e:
            logger.error(f"驱动操作线程错误: {e}")
            self.finished.emit(False)
    
    def on_config_item_clicked(self, item, column):
        """配置项点击事件处理"""
        # 获取完整路径
        path = self._get_item_path(item)
        
        # 获取配置值
        value = self._get_config_value_by_path(path)
        
        # 更新编辑器
        self.config_key_edit.setText(path)
        self._set_value_editor(value)
        
        # 启用应用按钮
        self.apply_button.setEnabled(True)
    
    def _get_item_path(self, item):
        """获取配置项的完整路径"""
        path_parts = []
        current_item = item
        
        # 向上遍历获取所有父节点
        while current_item:
            text = current_item.text(0)
            # 处理列表索引
            if text.startswith("[") and text.endswith("]"):
                path_parts.append(text)
            else:
                path_parts.append(text)
            current_item = current_item.parent()
        
        # 反转路径并连接
        path_parts.reverse()
        path = ".".join(path_parts)
        
        # 处理列表索引格式
        path = path.replace(".[", "[")
        
        return path
    
    def _get_config_value_by_path(self, path):
        """根据路径获取配置值"""
        try:
            # 简单路径处理，实际应用中需要更复杂的路径解析
            parts = path.split(".")
            value = self.config_manager.get_all()
            
            for part in parts:
                # 检查是否为列表索引
                if part.startswith("[") and part.endswith("]"):
                    index = int(part[1:-1])
                    if isinstance(value, list) and index < len(value):
                        value = value[index]
                    else:
                        return None
                else:
                    if isinstance(value, dict) and part in value:
                        value = value[part]
                    else:
                        return None
            
            return value
        except Exception as e:
            logger.error(f"获取配置值失败: {e}")
            return None
    
    def _set_value_editor(self, value):
        """设置值编辑器"""
        # 隐藏所有编辑器
        self.string_edit.setVisible(False)
        self.int_spin.setVisible(False)
        self.float_spin.setVisible(False)
        self.bool_check.setVisible(False)
        self.list_edit.setVisible(False)
        self.dict_edit.setVisible(False)
        self.color_button.setVisible(False)
        self.file_button.setVisible(False)
        
        # 根据值类型设置对应的编辑器
        if isinstance(value, bool):
            self.config_type_combo.setCurrentText("布尔值")
            self.bool_check.setChecked(value)
            self.value_editor_layout.replaceWidget(self.string_edit, self.bool_check)
            self.bool_check.setVisible(True)
        elif isinstance(value, int):
            self.config_type_combo.setCurrentText("整数")
            self.int_spin.setValue(value)
            self.value_editor_layout.replaceWidget(self.string_edit, self.int_spin)
            self.int_spin.setVisible(True)
        elif isinstance(value, float):
            self.config_type_combo.setCurrentText("浮点数")
            self.float_spin.setValue(value)
            self.value_editor_layout.replaceWidget(self.string_edit, self.float_spin)
            self.float_spin.setVisible(True)
        elif isinstance(value, list):
            self.config_type_combo.setCurrentText("列表")
            self.list_edit.setPlainText("\n".join(str(item) for item in value))
            self.value_editor_layout.replaceWidget(self.string_edit, self.list_edit)
            self.list_edit.setVisible(True)
        elif isinstance(value, dict):
            self.config_type_combo.setCurrentText("字典")
            dict_text = "\n".join(f"{k}={v}" for k, v in value.items())
            self.dict_edit.setPlainText(dict_text)
            self.value_editor_layout.replaceWidget(self.string_edit, self.dict_edit)
            self.dict_edit.setVisible(True)
        else:
            # 默认作为字符串处理
            self.config_type_combo.setCurrentText("字符串")
            self.string_edit.setText(str(value) if value is not None else "")
            self.value_editor_layout.replaceWidget(self.bool_check, self.string_edit)
            self.value_editor_layout.replaceWidget(self.int_spin, self.string_edit)
            self.value_editor_layout.replaceWidget(self.float_spin, self.string_edit)
            self.value_editor_layout.replaceWidget(self.list_edit, self.string_edit)
            self.value_editor_layout.replaceWidget(self.dict_edit, self.string_edit)
            self.value_editor_layout.replaceWidget(self.color_button, self.string_edit)
            self.value_editor_layout.replaceWidget(self.file_button, self.string_edit)
            self.string_edit.setVisible(True)
    
    def on_value_type_changed(self, index):
        """值类型改变事件处理"""
        type_text = self.config_type_combo.currentText()
        
        # 隐藏所有编辑器
        self.string_edit.setVisible(False)
        self.int_spin.setVisible(False)
        self.float_spin.setVisible(False)
        self.bool_check.setVisible(False)
        self.list_edit.setVisible(False)
        self.dict_edit.setVisible(False)
        self.color_button.setVisible(False)
        self.file_button.setVisible(False)
        
        # 显示选中的编辑器
        if type_text == "字符串":
            self.value_editor_layout.replaceWidget(self.bool_check, self.string_edit)
            self.value_editor_layout.replaceWidget(self.int_spin, self.string_edit)
            self.value_editor_layout.replaceWidget(self.float_spin, self.string_edit)
            self.value_editor_layout.replaceWidget(self.list_edit, self.string_edit)
            self.value_editor_layout.replaceWidget(self.dict_edit, self.string_edit)
            self.value_editor_layout.replaceWidget(self.color_button, self.string_edit)
            self.value_editor_layout.replaceWidget(self.file_button, self.string_edit)
            self.string_edit.setVisible(True)
        elif type_text == "整数":
            self.value_editor_layout.replaceWidget(self.string_edit, self.int_spin)
            self.int_spin.setVisible(True)
        elif type_text == "浮点数":
            self.value_editor_layout.replaceWidget(self.string_edit, self.float_spin)
            self.float_spin.setVisible(True)
        elif type_text == "布尔值":
            self.value_editor_layout.replaceWidget(self.string_edit, self.bool_check)
            self.bool_check.setVisible(True)
        elif type_text == "列表":
            self.value_editor_layout.replaceWidget(self.string_edit, self.list_edit)
            self.list_edit.setVisible(True)
        elif type_text == "字典":
            self.value_editor_layout.replaceWidget(self.string_edit, self.dict_edit)
            self.dict_edit.setVisible(True)
        elif type_text == "颜色":
            self.value_editor_layout.replaceWidget(self.string_edit, self.color_button)
            self.color_button.setVisible(True)
        elif type_text == "文件路径":
            self.value_editor_layout.replaceWidget(self.string_edit, self.file_button)
            self.file_button.setVisible(True)
    
    def select_color(self):
        """选择颜色"""
        color = QColorDialog.getColor()
        if color.isValid():
            self.string_edit.setText(color.name())
            self.string_edit.setVisible(True)
            self.color_button.setVisible(False)
            self.value_editor_layout.replaceWidget(self.color_button, self.string_edit)
    
    def select_file(self):
        """选择文件"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件")
        if file_path:
            self.string_edit.setText(file_path)
            self.string_edit.setVisible(True)
            self.file_button.setVisible(False)
            self.value_editor_layout.replaceWidget(self.file_button, self.string_edit)
    
    def apply_changes(self):
        """应用配置更改"""
        # 获取配置键和值
        config_key = self.config_key_edit.text()
        type_text = self.config_type_combo.currentText()
        
        # 根据类型获取值
        try:
            if type_text == "字符串":
                value = self.string_edit.text()
            elif type_text == "整数":
                value = self.int_spin.value()
            elif type_text == "浮点数":
                value = self.float_spin.value()
            elif type_text == "布尔值":
                value = self.bool_check.isChecked()
            elif type_text == "列表":
                text = self.list_edit.toPlainText()
                value = [line.strip() for line in text.splitlines() if line.strip()]
            elif type_text == "字典":
                text = self.dict_edit.toPlainText()
                value = {}
                for line in text.splitlines():
                    if "=" in line:
                        k, v = line.split("=", 1)
                        value[k.strip()] = v.strip()
            else:
                value = self.string_edit.text()
            
            # 设置配置值
            self.config_manager.set(config_key, value)
            
            # 更新配置树
            config_data = self.config_manager.get_all()
            self._update_config_tree(config_data)
            
            # 更新配置预览
            self._update_config_preview()
            
            # 更新状态
            self.status_label.setText(f"已更新配置: {config_key}")
            
            # 发送信号
            self.config_changed.emit(config_key, value)
            
            # 禁用应用按钮
            self.apply_button.setEnabled(False)
            
            logger.info(f"已更新配置: {config_key} = {value}")
            
        except Exception as e:
            logger.error(f"应用配置更改失败: {e}")
            QMessageBox.critical(self, "错误", f"应用配置更改失败: {str(e)}")
    
    def apply_common_config(self):
        """应用常用配置"""
        try:
            # 更新日志配置
            self.config_manager.set("logging.level", self.log_level_combo.currentText())
            self.config_manager.set("logging.file", self.log_file_edit.text())
            self.config_manager.set("logging.rotate", self.log_rotate_check.isChecked())
            
            # 更新机器人配置
            self.config_manager.set("robot.default_timeout", self.default_timeout_spin.value())
            self.config_manager.set("robot.default_retry", self.default_retry_spin.value())
            self.config_manager.set("robot.retry_interval", self.retry_interval_spin.value())
            
            # 更新配置树
            config_data = self.config_manager.get_all()
            self._update_config_tree(config_data)
            
            # 更新配置预览
            self._update_config_preview()
            
            # 更新状态
            self.status_label.setText("已应用常用配置")
            
            logger.info("已应用常用配置")
            
        except Exception as e:
            logger.error(f"应用常用配置失败: {e}")
            QMessageBox.critical(self, "错误", f"应用常用配置失败: {str(e)}")
    
    def load_config(self):
        """加载配置文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "加载配置文件", 
            "", 
            "配置文件 (*.json *.yaml *.yml);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 加载配置
                self.config_manager.load_config(file_path)
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新配置预览
                self._update_config_preview()
                
                # 更新统计信息
                self.stats_label.setText(str(self._count_config_items(config_data)))
                
                # 更新常用配置控件
                self._update_common_config_controls()
                
                # 更新配置路径
                self.current_config_path = file_path
                self.config_path_label.setText(file_path)
                
                # 更新上次修改时间
                import os
                import datetime
                try:
                    mtime = os.path.getmtime(file_path)
                    self.modified_time_label.setText(datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S'))
                except:
                    self.modified_time_label.setText("未知")
                
                # 更新状态
                self.status_label.setText(f"已加载配置: {file_path}")
                
                # 发送信号
                self.config_loaded.emit(file_path)
                
                logger.info(f"已加载配置文件: {file_path}")
                
            except Exception as e:
                logger.error(f"加载配置文件失败: {e}")
                QMessageBox.critical(self, "错误", f"加载配置文件失败: {str(e)}")
    
    def save_config(self):
        """保存配置文件"""
        if self.current_config_path:
            try:
                # 保存配置
                self.config_manager.save_config(self.current_config_path)
                
                # 更新状态
                self.status_label.setText(f"已保存配置: {self.current_config_path}")
                
                # 发送信号
                self.config_saved.emit(self.current_config_path)
                
                logger.info(f"已保存配置文件: {self.current_config_path}")
                
            except Exception as e:
                logger.error(f"保存配置文件失败: {e}")
                QMessageBox.critical(self, "错误", f"保存配置文件失败: {str(e)}")
        else:
            # 如果没有当前路径，调用另存为
            self.save_config_as()
    
    def save_config_as(self):
        """另存为配置文件"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, 
            "保存配置文件", 
            "config.json", 
            "JSON配置 (*.json);;YAML配置 (*.yaml *.yml);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 保存配置
                self.config_manager.save_config(file_path)
                
                # 更新当前路径
                self.current_config_path = file_path
                self.config_path_label.setText(file_path)
                
                # 更新状态
                self.status_label.setText(f"已保存配置: {file_path}")
                
                # 发送信号
                self.config_saved.emit(file_path)
                
                logger.info(f"已保存配置文件: {file_path}")
                
            except Exception as e:
                logger.error(f"保存配置文件失败: {e}")
                QMessageBox.critical(self, "错误", f"保存配置文件失败: {str(e)}")
    
    def reset_to_default(self):
        """重置为默认配置"""
        # 确认重置
        reply = QMessageBox.question(
            self, 
            "确认重置", 
            "确定要重置为默认配置吗？所有未保存的更改将会丢失。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            try:
                # 重置配置
                self.config_manager.reset()
                
                # 更新配置树
                config_data = self.config_manager.get_all()
                self._update_config_tree(config_data)
                
                # 更新配置预览
                self._update_config_preview()
                
                # 更新统计信息
                self.stats_label.setText(str(self._count_config_items(config_data)))
                
                # 更新常用配置控件
                self._update_common_config_controls()
                
                # 清空当前路径
                self.current_config_path = None
                self.config_path_label.setText("未设置")
                
                # 更新状态
                self.status_label.setText("已重置为默认配置")
                
                logger.info("已重置为默认配置")
                
            except Exception as e:
                logger.error(f"重置配置失败: {e}")
                QMessageBox.critical(self, "错误", f"重置配置失败: {str(e)}")
    
    def validate_config(self):
        """验证配置"""
        try:
            # 这里可以添加配置验证逻辑
            # 例如：检查必要的配置项是否存在，配置值是否合法等
            
            # 简单验证示例
            required_keys = ["logging.level", "robot.default_timeout"]
            missing_keys = []
            
            for key in required_keys:
                if not self.config_manager.has(key):
                    missing_keys.append(key)
            
            if missing_keys:
                error_msg = f"缺少必要的配置项: {', '.join(missing_keys)}"
                QMessageBox.warning(self, "验证警告", error_msg)
                self.status_label.setText(error_msg)
            else:
                QMessageBox.information(self, "验证成功", "配置验证通过")
                self.status_label.setText("配置验证通过")
                
            logger.info("配置验证完成")
            
        except Exception as e:
            logger.error(f"验证配置失败: {e}")
            QMessageBox.critical(self, "错误", f"验证配置失败: {str(e)}")
    
    def search_config(self, text):
        """搜索配置"""
        # 这里可以实现搜索逻辑
        # 例如：高亮显示匹配的配置项
        pass
    
    def _browse_file(self, line_edit):
        """浏览文件"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件")
        if file_path:
            line_edit.setText(file_path)